// Copyright 2019 The rhyme_lph Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// H [author] rhyme_lph
// Z [email]  rhymelph@gmail.com
// A [github] https://github.com/rhymelph

import 'package:base_plugin/base_plugin.dart';
import 'package:finance_app/generated/l10n.dart';
import 'package:finance_app/services/mlv_service.dart';
import 'package:finance_app/src/common/config.dart';
import 'package:finance_app/src/entities/expense_detail_entity.dart';
import 'package:finance_app/src/entities/ocr_attachment_entity.dart';
import 'package:finance_app/src/entities/setting_data_entity.dart';
import 'package:finance_app/src/http_service/http_attachment_service.dart';
import 'package:finance_app/src/http_service/http_category_service.dart';
import 'package:finance_app/src/router_gen/router_gen_providers.dart';
import 'package:finance_app/src/widgets/bottom_sheet/stack_bottom_sheet.dart';
import 'package:flutter/material.dart';

class ReviewPhotoProvider extends BaseProvider<List<SettingDataCategory>> {
  List<String> filePathList;

  final ScrollController scrollController = ScrollController();
  final StackBottomSheetController stackBottomSheetController =
      StackBottomSheetController();

  SettingDataCategory currentSelectCategory;

  List<int> recentIds;

  List<String> menuList = [];
  List<String> _menuListCamera = ['Edit Photo', 'Retake Photo'];
  List<String> _menuListPhoto = ['Edit Photo', 'Choose Again'];
  bool isFromPhoto;

  @override
  void initState() {
    recentIds = Config.expenseRecentIds;
    super.initState();
  }

  @override
  void dispose() {
    super.dispose();
    scrollController.dispose();
    stackBottomSheetController.dispose();
  }

  @override
  Future get dataFuture =>
      Config.category == null ? HttpCategoryService.categories() : null;

  @override
  FutureOr<List<SettingDataCategory>> transformData(
      List<SettingDataCategory> d, bool isCache) async {
    RProvider.myProvider.globalMap[ConfigKey.category] = d;
    await RProvider.myProvider.updateGlobalMap();
    return super.transformData(d, isCache);
  }

  void onInitData(String filepath, bool isFromPhoto, bool isCombine) async {
    this.isFromPhoto = isFromPhoto;
    if (isCombine == true) {
      this.filePathList = filepath.split(',');
      menuList = ['Retake Photo'];
    } else {
      this.filePathList = [filepath];
      if (isFromPhoto == true) {
        menuList = _menuListPhoto;
      } else {
        menuList = _menuListCamera;
      }
    }
  }

  void onChangeSelectCode(SettingDataCategory value) async {
    // if (currentSelectCategory?.id != value?.id) {
    //   currentSelectCategory = value;
    //   update();
    // }
    updateRecentUsedIds(value.id);
    obtainContext?.call((context) {
      BaseConfig.dialogBase
          .showLoadingDialog(context: context, text: S.current.loading);
    });
    OcrAttachmentEntity ocrData;
    String ocrText;
    try {
      ocrText = await MLVService().onOCRResult(filePathList.first);
    } catch (e) {}
    await post(
        HttpAttachmentService.createAttachment(filePathList.first,
            ocr: 1, preOcrText: ocrText, category: value?.key),
        autoHandler: AutoHandler.Toast, onSuccess: (result) {
      ocrData = getEntityFromResult<OcrAttachmentEntity>(result);
    });
    obtainContext?.call((context) {
      Navigator.of(context).pop();
    });
    if (ocrData != null) {
      if (ocrData.ocrData.type == 'expense') {
        Routes.navigateTo(RouterGenProviders.newExpensePage,
            params: {
              'ocrData': ocrData.ocrData,
              'attachments': filePathList,
            },
            replace: true);
      }
    }
  }

  void onSelectMenu(value) async {
    int index = menuList.indexOf(value);
    if (index == 0) {
      //edit photo
      String result =
          await Routes.navigateTo(RouterGenProviders.editPhotoPage, params: {
        'filepath': filePathList.first,
        'isFromPhoto': isFromPhoto,
      });
      if (result != null) {
        filePathList[0] = result;
        update();
      }
    } else if (index == 1) {
      if (isFromPhoto == true) {
        Routes.navigateTo(RouterGenProviders.selectPhotoPage, replace: true);
      } else {
        //retake photo
        Routes.navigateTo(RouterGenProviders.ocrCameraPage, replace: true);
      }
    }
  }

  void updateRecentUsedIds(int id) async {
    if (recentIds == null) {
      recentIds = [id];
    } else {
      recentIds.remove(id);
      recentIds.insert(0, id);
      if (recentIds.length > 5) {
        recentIds.removeLast();
      }
    }
    RProvider.myProvider.globalMap[ConfigKey.expenseRecentIds] = recentIds;
    await RProvider.myProvider.updateGlobalMap();
  }
}
